package com.woniuxy.filtes;

import com.woniuxy.util.MyJsonWebToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @ClassName JWTFilter
 * @Description TODO
 * @Author LI.hh
 * @Date 2022/9/6 20:13
 * @Version 1.0
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {
    //前端封装token的key
    private final String TOKENKEY= "Authorization";
    /**
     * 讲拦截器的时候用过，通常我们都在这里 统一处理跨域 的信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest)request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        response1.setHeader("Access-Control-Allow-Origin",request1.getHeader("Origin"));
        //OPTIONS就是预提交，浏览器发送的一个额外的请求，检查请求是否通常
        response1.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
        response1.setHeader("Access-Control-Allow-Headers",request1.getHeader("Access-Control-Request-Headers"));
        //如果是预提交的请求，我们直接返回一个正常状态即可
        if (request1.getMethod().equals(RequestMethod.OPTIONS.name())){
            response1.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request1, response1);
    }
    /**
     * 真正的Shiro的过滤器，第一步操作 是否允许访问 isAccessAllowed --> isLoginAttempt ---> executeLogin
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        //这个if判断的是 你前端的请求头中，有没有携带Authorization 请求头，这个请求中的value就是我们的token
        if (isLoginAttempt(request,response)){//直接重写，免得报错
            try {
                //执行登录操作
                executeLogin(request,response);
            } catch (Exception e) {
                e.printStackTrace();
                response401(request,response);
                return false;
            }
        }
        return true;
    }
    /**
     * 是否登录请求，判断请求头中有没有封装token
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest)request;
        String token = request1.getHeader(TOKENKEY);
        return token != null;
    }
    /**
     * 最终执行登录请求subject.login的方法
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest)request;
        //从请求头中获取token
        String token = request1.getHeader(TOKENKEY);
        //就是之前SecurityUtils.getSubject();自己模仿着UsernamePasswordToken创建一个 MyJsonWebToken
        getSubject(request,response).login(new MyJsonWebToken(token));//进入自定义域中！
        return true;
    }
    private void response401(ServletRequest request, ServletResponse response){
        HttpServletResponse response1 = (HttpServletResponse) response;
        //重定向
        try {
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
